// p2p_client.cpp : Defines the entry point for the console application.
//


#include "../LIB/prpsock/prpsock.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
using namespace BAM;

class cFileLoginManager : public BAM::cLoginManager
{
private:
	map<string, string> vMap;

public:
	cFileLoginManager(const char* filename)
	{
		ifstream f(filename);
		if(!f)
			throw cException("Unable to open password file");
		string login, pass;
		while(!f.eof())
		{
			f >> login;
			if(f.eof())
			throw cException("Wrong password file format");
			f >> pass;
			vMap.insert(pair<string, string>(login, pass));
		}
	}

	BAM::cPacket getPassword(const BAM::cPacket &login)
	{
		BAM::cPacket P = login;
		P.insertTail((const BAM::byte*)"", 1);
		map<string, string>::const_iterator it = vMap.find((const char*)P.getData());
		if(it == vMap.end())
			throw BAM::EXC_Login;
		return BAM::cPacket((const BAM::byte*)(it->second.c_str()), strlen(it->second.c_str()));
	}
};


int main(int argc, char* argv[])
{
	cFileLoginManager* lm;
	cFileLoginManager* cs;
	
	//BAM::iSocket *T, *Sock, *Forw, *SSP;

	try
	{
		lm = new cFileLoginManager("passwd");
	}
	catch(exception& e)
	{
		cout << "Can't open passwd file: " << e.what() << endl;
		return 1;
	}
	try
	{
		cs = new cFileLoginManager("pass");
	}
	catch(exception& e)
	{
		cout << "Can't open pass file: " << e.what() << endl;
		return 1;
	}

	BAM::cPrpSocket* Forw =  new BAM::cPrpSocket(0, lm, BAM::cPacket((BAM::byte*)"user1", strlen("user1")), 1, BAM::Prp_Socket_Client);
	
	
	cout << "Enter packet data, 'quit' to quit"
		<< endl;

	string s;
	while (1)
	{
		cin >> s;
		if (s=="quit") break;
		cout << "Sending " << s << endl;
		BAM::cPacket p((BAM::byte *)s.c_str(), s.length() + 1);
		Forw->send(p);
		s = "";
	}
	
	

	return 0;
}

